<template>
  <div
    v-loading="pageLoading"
    :element-loading-text="loadingOption.text"
    :element-loading-spinner="loadingOption.spinner"
    :element-loading-background="loadingOption.background"
    class="article_main"
  >
    <el-card shadow="never" class="card">
      <div slot="header">
        <span>新增文章</span>
      </div>
      <!-- card body -->
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
        :inline="true"
        size="normal"
      >
        <el-form-item prop="author" size="small" label="作者">
          <el-input
            v-model="form.author"
            placeholder="作者姓名"
            class="form_ipt"
          />
        </el-form-item>
        <el-form-item size="small" prop="title" label="标题">
          <el-input
            v-model="form.title"
            placeholder="文章标题"
            class="form_ipt"
          />
        </el-form-item>
        <el-form-item size="small" style="margin-left: 40px" label="是否显示">
          <el-switch
            v-model="form.isShow"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <br>
        <el-form-item size="small" label="摘要">
          <el-input
            v-model="form.summary"
            placeholder="摘要"
            :autosize="{ minRows: 3, maxRows: 3 }"
            type="textarea"
            class="form_ipt_long"
          />
        </el-form-item>
        <br>
        <el-form-item size="small" label="封面图片">
          <el-upload
            ref="materialUpload"
            class="upload-demo"
            :action="uploadUrl"
            :headers="headers"
            :on-success="handleUploadSucc"
          >
            <el-button size="small" type="primary">点击上传素材</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
          <img
            v-if="form.coverImg"
            :src="form.coverImg"
            class="uploadImg"
            alt=""
          >
        </el-form-item>
        <br>
        <el-form-item
          size="small"
          style="display: block; width: 100%"
          label="切换富文本类型"
        >
          <el-radio-group v-model="form.editorType" @change="toggleEditType">
            <el-radio :label="0">富文本</el-radio>
            <el-radio :label="1">markdown</el-radio>
          </el-radio-group>
          <span class="warin">
            <i class="el-icon-warning" />
            注意!切换编辑器会清空编辑内容
          </span>
        </el-form-item>
        <!-- 给富文本新增图片 -->
        <el-upload
          v-show="form.editorType === 0"
          ref="innerUpload"
          class="upload-demo"
          :action="uploadUrl"
          :headers="headers"
          :on-success="handleInnerImg"
        >
          <el-button
            style="margin-bottom: 5px"
            type="primary"
            size="small"
          >插入图片↓</el-button>
        </el-upload>
        <!-- 富文本框 -->
        <div v-if="form.editorType === 0">
          <TinEditor ref="tin" />
        </div>
        <div v-if="form.editorType === 1">
          <!-- <MarkdownEditor ref="md" /> -->
          <mavon-editor ref="mavon" @imgAdd="imgAdd" @imgDel="imgDel" v-model="form.content1" @change="getMarkDownHtml" />
        </div>

        <div class="flexCenter">
          <el-form-item size="small">
            <el-button
              :loading="loading"
              type="primary"
              @click="onSubmit"
            >{{ id?"立即修改":"立即新增" }}</el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import mixin from '@/mixins/index'
import contentApi from '@/api/content/index'
import TinEditor from '@/components/Tinymce'
import {
  uploadFileOss
} from "@/api/content"
// import MarkdownEditor from '@/components/MarkdownEditor'
export default {
    name: 'AddArticle',
    components: { 
      TinEditor, 
      // MarkdownEditor 
    },
    mixins: [mixin],

    data() {
        return {
            pageLoading: false, // 页面加载
            id: '',
            loading: false,
            form: {
                author: '',
                title: '',
                summary: '',
                coverImg: '',
                isShow: 1, // 是否展示
                editorType: 0, // 0富文本  1markdown
                content1: '', // 富文本原文
                content2: '' // 富文本html
            },
            rules: {
                title: [
                    { required: true, message: '请输入文章标题', trigger: 'blur' }
                    // { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
                ],
                author: [
                    { required: true, message: '请输入作者姓名', trigger: 'blur' }
                    // { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
                ]
            }
        }
    },
    created() {
        this.id = this.$route.params.id
        console.log(this.id)
        if (this.id) {
            this.getArticleDetail()
        }
    },
    methods: {
      imgAdd(pos, $file){
        var formdata = new FormData();
        formdata.append('file', $file);
        console.log($file,uploadFileOss)
        uploadFileOss(formdata)
        .then(res =>{
          console.log(res)
          this.$refs.mavon.$img2Url(pos, res.data.fileUrl);
        })
      },
      imgDel(){

      },
      toggleEditType(e){
        if(e){
          this.form.content1 = ""
        }
      },
      getMarkDownHtml(val,html){
        this.form.content2 = html;
      },
        getArticleDetail() {
            this.pageLoading = true
            contentApi.articleDetailApi(this.id).then((res) => {
                if (res.success) {
                    this.form = res.data.productArticle
                    // 是否展示转换为1或者0
                    this.form.isShow = this.form.isShow ? 1 : 0
                    // 渲染富文本框和 Markdown内容
                    this.$nextTick(() => {
                        if (this.form.editorType === 0) {
                            this.setTin(this.form.content1)
                        } 
                    })
                } else {
                    this.$message.error('获取文章内容失败')
                }
                this.pageLoading = false
            })
        },
        // 在富文本内插入圖片
        handleInnerImg(res) {
            if (res.success) {
                this.$refs.innerUpload.clearFiles()
                this.$refs.tin.imageSuccessCBK(res.data.fileUrl)
            } else {
                this.$message.error('素材上传失败')
            }
        },
        // 封面照片上传成功
        handleUploadSucc(res, file, fileList) {
            if (res.success) {
                this.$refs.materialUpload.clearFiles()
                this.form.coverImg = res.data.fileUrl
            } else {
                this.$message.error('素材上传失败')
            }
        },
        // 提交按钮
        onSubmit() {
            if (this.form.editorType === 0) {
                this.form.content1 = this.form.content2 = this.getTin()
            } 
            // 不能爲空
            if (!this.form.content1 || !this.form.content2) {
                this.$message.warning('文章内容不能爲空')
                return false
            }
            // 判断rules
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.loading = true
                    if (!this.id) {
                        contentApi.addArticleApi({ ...this.form }).then((res) => {
                            if (res.success) {
                                console.log(res)
                                this.$router.push({ name: 'articleList' })
                            } else {
                                this.$message.error('添加失败')
                            }
                            this.loading = false
                        })
                    } else {
                        contentApi.editArticleApi({ ...this.form })
                            .then((res) => {
                                if (res.success) {
                                    console.log(res)
                                    this.$router.push({ name: 'articleList' })
                                } else {
                                    this.$message.error('修改失败')
                                }
                                this.loading = false
                            })
                    }
                } else {
                    this.$message.warning('请填写必要信息')
                }
            })
        },
        // // 切换 富文本框和markdown按钮
        // editorChange(val) {
        //     console.log(val)
        // },
        // 获取富文本框内容
        getTin() {
            var rs = this.$refs.tin.getContent()
            return rs
        },
        // 设置富文本框内容
        setTin(v) {
            this.$refs.tin.setDelayContent(v)
        },
        // 获取md富文本框内容
        getMd() {
            var html = this.$refs.md.getHtml()
            var val = this.$refs.md.getValue()
            return {
                html,
                val
            }
        },
        setMd(val) {
            this.$refs.md.setValue(val)
        }
    }
}
</script>

<style  scoped lang="scss">
.article_main {
  min-height: 1000px;
  .form_ipt {
    width: 300px;
  }
  .form_ipt_long {
    width: 800px;
    // height: 200px;
  }
  .card {
    margin: 30px;
  }

  .uploadImg {
    width: 200px;
    height: 200px;
    // background-color: red;
    // margin-left: 150px;
    // float: right;
  }
  .flexCenter {
    margin-top: 15px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .warin {
    margin-left: 40px;
    color: rgb(230, 162, 60);
  }
}
</style>
